package org.ielse.frame.test;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.ielse.frame.BaseActivity;
import org.ielse.frame.R;
import org.ielse.frame.ViewCallback;
import org.ielse.frame.t.view.markushi.ActionView;
import org.ielse.frame.t.view.markushi.action.Action;
import org.ielse.frame.t.view.markushi.action.BackAction;
import org.ielse.frame.t.view.markushi.action.DrawerAction;
import org.ielse.frame.t.view.ultra.PtrDefaultHandler;
import org.ielse.frame.t.view.ultra.PtrFrameLayout;
import org.ielse.frame.t.view.ultra.PtrHandler;
import org.ielse.frame.t.view.ultra.header.StoreHouseHeader;
import org.ielse.frame.t.view.ultra.util.RefreshPoint;
import org.ielse.frame.t.volley.MultipartInfo;
import org.ielse.frame.util.BaseUtil;
import org.ielse.frame.util.DateUtil;
import org.ielse.frame.util.DialogUtil;
import org.ielse.frame.util.DialogUtil.BottomMenuBuidler.BottomMenu;
import org.ielse.frame.util.LogUtil;
import org.ielse.frame.util.NetworkUtil;
import org.ielse.frame.view.LeftMenuLayout;
import org.ielse.frame.view.LoadingView;
import org.ielse.frame.view.PagerLayout;
import org.ielse.frame.view.SwitchView;
import org.ielse.frame.view.SwitchView.OnStateChangedListener;
import org.ielse.frame.view.TitleLayout;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.nineoldandroids.view.ViewHelper;

public class MainActivity extends BaseActivity {

	private PagerLayout layPager;
	private DrawerLayout mDrawerLayout;
	private TitleLayout layTitle;
	private ActionView mFirstViewAction;

	private LeftMenuLayout layLeftMenu;
	private SwitchView viewSwitch1;

	private boolean drawerOpened;

	@Override protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_main);
		super.onCreate(savedInstanceState);

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerLayout.setScrimColor(Color.TRANSPARENT);
		final View mContent = mDrawerLayout.getChildAt(0);
		mContent.post(new Runnable() {
			@Override public void run() {
				ViewHelper.setPivotX(mContent, mContent.getMeasuredWidth());
				ViewHelper.setPivotY(mContent, mContent.getMeasuredHeight() / 2);
			}
		});
		mDrawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
			@Override public void onDrawerStateChanged(int newState) {
				LogUtil.t("mDrawerLayout onDrawerStateChanged:" + newState);
			}

			@Override public void onDrawerSlide(View drawerView, float slideOffset) {
				View mContent = mDrawerLayout.getChildAt(0);
				final float contentScale = 1 - slideOffset * 0.1f;

				if (drawerView.getTag().equals("LEFT")) {
					ViewHelper.setTranslationX(mContent, drawerView.getMeasuredWidth() * slideOffset);
					ViewHelper.setScaleY(mContent, contentScale);
				}

				if (layPager.isOnlyOnePageOrEmpty()) {
					mFirstViewAction.setAlpha(1 - slideOffset);
				}

			}

			@Override public void onDrawerOpened(android.view.View drawerView) {
				drawerOpened = true;
				layLeftMenu.startContentAnimation();
				mFirstViewAction.setAlpha(0);
			}

			@Override public void onDrawerClosed(android.view.View drawerView) {
				drawerOpened = false;
				layLeftMenu.resetContentAnimation();
				mFirstViewAction.setAlpha(1);
			}
		});

		layLeftMenu = new LeftMenuLayout(context);
		((ViewGroup) findViewById(R.id.lay_left_menu)).addView(layLeftMenu);
		layPager = new PagerLayout(context);
		((ViewGroup) findViewById(R.id.lay_content)).addView(layPager);

		layPager.pushNewContent(initMain(), false);
		layTitle = new TitleLayout(context);
		mFirstViewAction = initLeftMenuActionView(new DrawerAction(), ActionView.ROTATE_COUNTER_CLOCKWISE);
		layTitle.pushContent(mFirstViewAction, context.getString(R.string.app_name), null, false);
		layPager.addViewToFront(layTitle);
	}

	@Override public void onViewCallback(int action, Object... args) {
		super.onViewCallback(action, args);
		switch (action) {
		case ACT_DRAWER_LAYOUT_OPEN_LEFT:
			mDrawerLayout.openDrawer(Gravity.LEFT);
			break;
		case ACTION_LAY_PAGE_MOVE:
			layTitle.setToLastAnimationProgress((Float) args[0]);
			break;
		case ACTION_LAY_PAGE_UP_TO_CURRENT:
			layTitle.returnToCurrentContent();
			break;
		case ACTION_LAY_PAGE_UP_TO_LAST:
			layTitle.popToLastContent();
			mDrawerLayout.setDrawerLockMode(layPager.isOnlyOnePageOrEmpty() ? DrawerLayout.LOCK_MODE_UNLOCKED
					: DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.LEFT);
			break;
		case ACT_LEFT_MENU_AUTO_BACKUP:
			layTitle.pushNewContent(initLeftMenuActionView(new BackAction(), ActionView.ROTATE_CLOCKWISE), getString(R.string.cancel),
					null, false);
			layPager.pushNewContent(initContentForAutoBackUp(), false);
			mDrawerLayout.closeDrawers();
			mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.LEFT);
			break;
		case ACT_LEFT_MENU_RADAR:
			layTitle.pushNewContent(initLeftMenuActionView(new BackAction(), ActionView.ROTATE_CLOCKWISE), getString(R.string.cancel),
					null, false);
			layPager.pushNewContent(initContentRada(), false);
			mDrawerLayout.closeDrawers();
			mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.LEFT);
			break;
		default:
			LogUtil.e("MainActivity onViewCallback() undefined action!");
			break;
		}
	}

	private View initMain() {
		View view = inflate(R.layout.layout_main_center);

		viewSwitch1 = (SwitchView) view.findViewById(R.id.view_switch1);
		viewSwitch1.setState(appSettings.isShinyTrace());

		viewSwitch1.setOnStateChangedListener(new OnStateChangedListener() {
			@Override public void toggleToOn() {
				viewSwitch1.toggleSwitch(true);
				appSettings.setShinyTrace(true);
				appSettings.update(appSettings.getId());
			}

			@Override public void toggleToOff() {
				viewSwitch1.toggleSwitch(false);
				appSettings.setShinyTrace(false);
				appSettings.update(appSettings.getId());
			}
		});

		view.findViewById(R.id.btn_start_activity_b).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View arg0) {
				startActivity(NormalActivity.class);
			}
		});

		view.findViewById(R.id.btn_parallax).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View arg0) {
				startActivity(SplashActivity.class);
			}
		});

		view.findViewById(R.id.btn_show_confrim_dialog).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				a = DialogUtil.ConfirmBuilder.init(context).createSimple(R.string.app_name, true, true).setTitleText("comfirm dialog")
						.setCancelListener(new OnClickListener() {
							@Override public void onClick(View v) {
								a.dismiss();
							}
						}).setConfirmListener(new OnClickListener() {
							@Override public void onClick(View v) {
								a.dismiss();
							}
						}).show();
			}
		});

		view.findViewById(R.id.btn_show_bottom_dialog).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				List<BottomMenu> menuList = new ArrayList<DialogUtil.BottomMenuBuidler.BottomMenu>();
				menuList.add(new BottomMenu(getString(R.string.frame_save_photo_to_album), new OnClickListener() {
					@Override public void onClick(View v) {
						requestTest();
					}
				}));
				menuList.add(new BottomMenu(getString(R.string.frame_settings_shiny_trace), null));
				b = DialogUtil.BottomMenuBuidler.init(context).create(menuList, true, true).setCancelListener(new OnClickListener() {
					@Override public void onClick(View v) {
						b.dismiss();
					}
				}).show();
			}
		});

		view.findViewById(R.id.btn_click_show_content).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				layPicture.showPicture("http://www.ppd.cn/uploads/allimg/101113/1002191333-6.jpg", v);
			}
		});

		view.findViewById(R.id.btn_refresh).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				startActivity(RefreshActivity.class);
			}
		});
		final ImageView imageUploadShow = (ImageView) view.findViewById(R.id.img_upload_show);
		view.findViewById(R.id.btn_uploadfile).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
//				final String testFile = "/storage/emulated/0/temp.png";
//				String url = "http://192.168.8.36:8081/youqu_interface/app/service.do";
//				 List<MultipartInfo> params = new ArrayList<MultipartInfo>();
//				 params.add(new MultipartInfo(MultipartInfo.TYPE_FILE, "file",
//				 testFile));
//				 params.add(new MultipartInfo(MultipartInfo.TYPE_TEXT, "text",
//						 "{\"imageName\":\"淡淡的.jpg\",\"msgId\":\"APP0249\",\"targetId\":\"73\",\"targetType\":\"1\",\"userId\":\"706\"}"));
//				 upload(url, params, new VolleyListenerAdapter<String>() {
//				 @Override public void onResponse(String response, boolean
//				 isFresh) {
//				 LogUtil.e(response);
//				 }
//				 });

//				RequestParams params = new RequestParams();
//				params.addQueryStringParameter("text",
//						"{\"imageName\":\"淡淡的.jpg\",\"msgId\":\"APP0249\",\"targetId\":\"73\",\"targetType\":\"1\",\"userId\":\"706\"}");
//				// 只包含字符串参数时默认使用BodyParamsEntity，
//				// 类似于UrlEncodedFormEntity（"application/x-www-form-urlencoded"）。
//				// 加入文件参数后默认使用MultipartEntity（"multipart/form-data"），
//				// 如需"multipart/related"，xUtils中提供的MultipartEntity支持设置subType为"related"。
//				// 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity（如：
//				// MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity）。
//				params.addBodyParameter("file", new File(testFile));
//				HttpUtils http = new HttpUtils();
//				http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
//					@Override public void onFailure(HttpException arg0, String arg1) {
//						LogUtil.e("onFailure()");
//					}
//
//					@Override public void onSuccess(ResponseInfo<String> arg0) {
//						LogUtil.e("onSuccess()");
//					}
//				});
			}
		});

		view.findViewById(R.id.btn_request).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				final String url = "http://www.baidu.com";
				StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
					@Override public void onResponse(String response) {
						LogUtil.i("onResponse() " + url + "\n" + response);
						showToast(response);
					}
				}, new Response.ErrorListener() {
					@Override public void onErrorResponse(VolleyError error) {
						LogUtil.e("onErrorResponse() " + url + "\n" + error.getMessage());
						TextView txInfo = new TextView(context);
						txInfo.setText(NetworkUtil.isNoInternet() ? R.string.error_net : R.string.error_request);
						txInfo.setTextColor(0xffffffff);
						txInfo.setBackgroundColor(0xff0d7dd1);
						final int spacing = BaseUtil.dipToPx(8);
						txInfo.setPadding(spacing * 2, spacing, spacing * 2, spacing);
						txInfo.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
						Toast t = new Toast(context);
						t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
						t.setDuration(Toast.LENGTH_LONG);
						t.setView(txInfo);
						t.show();

						if (requestQueue.getCache().get(url) != null) {
							String cache = new String(requestQueue.getCache().get(url).data);
							showToast(cache);
						}
					}
				}) {
					@Override protected Map<String, String> getParams() throws AuthFailureError {
						showToast("string request load params!!");
						return super.getParams();
					}

				};

				requestQueue.add(stringRequest);
			}
		});

		view.findViewById(R.id.btn_start_recy).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				startActivity(Recycler33333Activity.class);
			}
		});

		return view;
	}

	@Override protected boolean onChildBackPressed() {
		if (drawerOpened) {
			drawerOpened = false;
			mDrawerLayout.closeDrawers();
			return true;
		}
		else if (!layPager.isOnlyOnePageOrEmpty()) {
			layTitle.popToLastContent();
			layPager.popToLastContent();
			return true;
		}
		return false;
	}

	private View initContentRada() {
		View view = inflate(R.layout.layout_main_rada);
		view.findViewById(R.id.img_qzone).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				showToast("image qzone click");
				String url1 = "http://59.174.243.148:8608/resources/news/343/20150730022901274155.jpeg";
				String url2 = "http://images.china.cn/news/attachement/jpg/site3/20110808/3382250932702168458.jpg";
				String url4 = "http://a.hiphotos.baidu.com/baike/c0%3Dbaike80%2C5%2C5%2C80%2C26/sign=792ee7c4f203738dca470470d272db34/5882b2b7d0a20cf4f18266bb72094b36acaf9940.jpg";
				String url3 = "https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=302806050,3854317552&fm=58";
				List<String> urlList = new ArrayList<String>();
				urlList.add(url2);
				urlList.add(url1);
				urlList.add(url4);
				urlList.add(url3);
				layPicture.showPicture(urlList, v);
			}
		});

		try {
			TextView txTimeTest = (TextView) view.findViewById(R.id.tx_timetest);
			String info = "";
			info += DateUtil.timeInfo(DateUtil.parse("201507231246", DateUtil.yyyyMMddHHmm)) + "201507231246\n";
			info += DateUtil.timeInfo(DateUtil.parse("201507230811", DateUtil.yyyyMMddHHmm)) + "201507230811\n";
			info += DateUtil.timeInfo(DateUtil.parse("201507220723", DateUtil.yyyyMMddHHmm)) + "201507220723\n";
			info += DateUtil.timeInfo(DateUtil.parse("201507211250", DateUtil.yyyyMMddHHmm)) + "201507211250\n";
			info += DateUtil.timeInfo(DateUtil.parse("201507201246", DateUtil.yyyyMMddHHmm)) + "201507201246\n";
			info += DateUtil.timeInfo(DateUtil.parse("201507191246", DateUtil.yyyyMMddHHmm)) + "201507191246\n";
			info += DateUtil.timeInfo(DateUtil.parse("201507181246", DateUtil.yyyyMMddHHmm)) + "201507181246\n";
			info += DateUtil.timeInfo(DateUtil.parse("201507171246", DateUtil.yyyyMMddHHmm)) + "201507171246\n";
			info += DateUtil.timeInfo(DateUtil.parse("201507161246", DateUtil.yyyyMMddHHmm)) + "201507161246\n";
			info += DateUtil.timeInfo(DateUtil.parse("201507151246", DateUtil.yyyyMMddHHmm)) + "201507151246\n";
			info += DateUtil.timeInfo(DateUtil.parse("201507141246", DateUtil.yyyyMMddHHmm)) + "201507141246\n";
			info += DateUtil.timeInfo(DateUtil.parse("201507131246", DateUtil.yyyyMMddHHmm)) + "201507131246\n";
			info += DateUtil.timeInfo(DateUtil.parse("201507121246", DateUtil.yyyyMMddHHmm)) + "201507121246\n";
			info += DateUtil.timeInfo(DateUtil.parse("201506121246", DateUtil.yyyyMMddHHmm)) + "201506121246\n";
			info += DateUtil.timeInfo(DateUtil.parse("201505121246", DateUtil.yyyyMMddHHmm)) + "201505121246\n";
			info += DateUtil.timeInfo(DateUtil.parse("201405121246", DateUtil.yyyyMMddHHmm)) + "201405121246\n";
			txTimeTest.setText(info);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return view;
	}

	private Dialog a, b;

	private View initContentForAutoBackUp() {
		View view = inflate(R.layout.layout_main_back_up);

		final LoadingView tlv = (LoadingView) view.findViewById(R.id.view_loading);

		view.findViewById(R.id.btn_intercepter).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				tlv.startDelay();
			}
		});

		final PtrFrameLayout mPtrFrameLayout = (PtrFrameLayout) view.findViewById(R.id.material_style_ptr_frame);
		final ScrollView mScrollView = (ScrollView) view.findViewById(R.id.rotate_header_scroll_view);
		// header
		// final MaterialHeader header = new MaterialHeader(context);
		// int[] colors = new int[] { 0xffff00cc, 0xffcc00ff, 0xff00ffcc };
		// header.setColorSchemeColors(colors);
		// header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
		// header.setPadding(0, BaseUtil.dipToPx(15), 0, BaseUtil.dipToPx(10));
		// header.setPtrFrameLayout(mPtrFrameLayout);
		// header
		final StoreHouseHeader header = new StoreHouseHeader(context);
		header.setTextColor(0xff666666);
		header.setPadding(0, BaseUtil.dipToPx(15), 0, 0);
		header.initWithPointList(RefreshPoint.getLoadingText());

		mPtrFrameLayout.setDurationToCloseHeader(1500);
		mPtrFrameLayout.setHeaderView(header);
		mPtrFrameLayout.addPtrUIHandler(header);
		mPtrFrameLayout.postDelayed(new Runnable() {
			@Override public void run() {
				mPtrFrameLayout.autoRefresh(false);
			}
		}, 100);

		mPtrFrameLayout.setPtrHandler(new PtrHandler() {
			@Override public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
				return PtrDefaultHandler.checkContentCanBePulledDown(frame, mScrollView, header);
				// return true;
			}

			@Override public void onRefreshBegin(final PtrFrameLayout frame) {
				frame.postDelayed(new Runnable() {
					@Override public void run() {
						frame.refreshComplete();
					}
				}, 3000);
			}
		});

		return view;
	}

	private ActionView initLeftMenuActionView(Action action, int rotation) {

		final ActionView viewAction = new ActionView(context);
		final int size = BaseUtil.dipToPx(42);
		FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(size, size);
		lp.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
		viewAction.setLayoutParams(lp);
		final int padding = BaseUtil.dipToPx(8);
		viewAction.setPadding(padding, padding, padding, padding);
		viewAction.setColor(0xffffffff);
		viewAction.setAction(action, false, rotation);

		viewAction.setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				if (layPager.isOnlyOnePageOrEmpty()) {
					onViewCallback(ViewCallback.ACT_DRAWER_LAYOUT_OPEN_LEFT);
				}
				else {
					layTitle.popToLastContent();
					layPager.popToLastContent();
				}
			}
		});
		return viewAction;
	}

	//
	void requestTest() {
		final String url = "http://192.168.8.36:8081/youqu_interface/app/service.do";
		final Map<String, String> params = BaseUtil.initMap("text", gson.toJson(new Req()));
		request(Method.POST, url, params, Resp.class, new VolleyListenerAdapter<Resp>() {
			@Override public void onResponse(Resp response, boolean isFresh) {
				super.onResponse(response, isFresh);
			}
		});
	}

	class Req {
		String mail = "whsl2014001@fiberhome.com";
		String msgId = "APP001";
	}

	public class Resp {
		public int code;
		public String message;
		public ResultMap resultMap;

		public class ResultMap {
			public ActivityInfo activityInfo;
		}

		public class ActivityInfo {
			public String id;
		}
	}
}
